<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="注意：只允许为第三级分类设置参数!" type="warning" :closable='false' show-icon>
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!--  -->
          <el-cascader v-model="value" :options="options" :props="props" @change="handleChange" width='10%'></el-cascader>
        </el-col>
      </el-row>
      <!-- tab的展示页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态页面 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" @click="showData" :disabled='judgeData'>添加动态参数</el-button>
          <el-table :data="manyCateData" style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <el-tag v-for="(item,index) in scoped.row.attr_vals" :key="index" closable @close='delCate(scoped.row,index)'>{{item}}</el-tag>
                <!-- 添加的按钮 -->
                <el-input class="input-new-tag" v-if="scoped.row.inputVisible" v-model="scoped.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scoped.row)" @blur="handleInputConfirm(scoped.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50px" label="序号"></el-table-column>
            <el-table-column label="名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="warning" icon="el-icon-edit" size="mini" @click="editorData(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCateData(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态页面 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" @click="showData" :disabled='judgeData'>添加静态属性</el-button>
          <el-table :data="onlyCateData" border>
             <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <el-tag v-for="(item,index) in scoped.row.attr_vals" :key="index" closable @close='delCate(scoped.row,index)'>{{item}}</el-tag>
                <!-- 添加的按钮 -->
                <el-input class="input-new-tag" v-if="scoped.row.inputVisible" v-model="scoped.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scoped.row)" @blur="handleInputConfirm(scoped.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50px" label="序号"></el-table-column>
            <el-table-column label="名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="warning" icon="el-icon-edit" size="mini" @click="editorData(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCateData(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态属性的弹窗 -->
    <el-dialog title="添加" :visible.sync="dialogVisible" width="30%" @close='editDel'>
      <el-form :model="cateVale" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="cateVale.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateDeta">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog title="编辑" :visible.sync="editorVisible" width="30%" @close='editDel'>
      <el-form :model="cateVale" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="新的参数" prop="attr_name">
          <el-input v-model="cateVale.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorVisible = false">取 消</el-button>
        <el-button type="primary" @click="editorCateDeta">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 联级选择器选项
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 联级选择的数据id
      value: '',
      // 商品的数据
      options: [],
      // tab的默认展示页
      activeName: 'many',
      // 接收动态参数
      manyCateData: [],
      // 接收静态属性
      onlyCateData: [],
      // 添加动态或者静态的接收名称
      cateNameData: '',
      // 添加静态或者动态展示框的呈现
      dialogVisible: false,
      // 表单验证规则
      rules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      cateVale: {
        attr_name: ''
      },
      // 编辑窗口的显示与隐藏
      editorVisible: false,
      // 编辑点击的id值
      cateIDDate: Number
    }
  },
  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.options = res.data
    },
    // 联机选择器
    handleChange () {
      if (this.value.length !== 3) {
        this.value = []
        this.onlyCateData = []
        this.manyCateData = []
      }
      this.getCateData()
    },
    handleClick () {
      this.getCateData()
    },
    // 获取静态属性与动态参数的数据
    async getCateData () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      res.data.forEach((val) => {
        val.attr_vals = val.attr_vals ? val.attr_vals.split(',') : []
        // 控制按钮的显示与隐藏
        val.inputVisible = false
        // 按钮的输入数据
        val.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyCateData = res.data
      } else {
        this.onlyCateData = res.data
      }
      console.log(res.data)
    },
    // 添加分类
    async addCateDeta () {
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.cateVale.attr_name,
          attr_sel: this.activeName
        }
      )
      console.log(res)
      console.log(this.cateId)
      if (res.meta.status !== 201) return this.$message.error('创建失败')
      this.$message.success('创建成功')
      this.dialogVisible = false
      this.getCateData()
    },
    showData () {
      this.dialogVisible = true
    },
    // 删除分类
    async delCateData (id) {
      const { data: res } = await this.$http.delete(
        `categories/${id.cat_id}/attributes/${id.attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')

      this.getCateData()
    },
    // 编辑分类的确认按钮
    editorCateDeta () {
      this.$refs.ruleForm.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$http.put(
            `categories/${this.cateIDDate.cat_id}/attributes/${this.cateIDDate.attr_id}`,
            {
              attr_name: this.cateVale.attr_name,
              attr_sel: this.activeName
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error('修改失败')
          }
          this.$message.success('修改成功')
          this.editorVisible = false
          this.getCateData()
        }
      })
    },
    // 编辑分类的点击
    editorData (id) {
      this.cateIDDate = id
      this.editorVisible = true
    },
    // 编辑分类的弹窗消失事件,并且重置表单
    editDel () {
      this.$refs.ruleForm.resetFields()
    },
    // 按钮的点击事件
    showInput (scoped) {
      scoped.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 输入框的enter事件
    handleInputConfirm (scoped) {
      if (scoped.inputValue.trim().length === 0) {
        scoped.inputValue = ''
        scoped.inputVisible = false
        return
      }
      scoped.attr_vals.push(scoped.inputValue)
      scoped.inputValue = ''
      scoped.inputVisible = false
      // 需要发起请求，保存这次数据
      this.saveAttrVals(scoped)
    },
    // 删除对应的参数
    delCate (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 参数的数据的axios请求
    async saveAttrVals (scoped) {
      const { data: res } = await this.$http.put(`categories/${scoped.cat_id}/attributes/${scoped.attr_id}`, {
        attr_name: scoped.attr_name,
        attr_sel: scoped.attr_sel,
        attr_vals: scoped.attr_vals.join(',')
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('新增失败')
      }
      this.$message.success('修改成功')
    }
  },
  computed: {
    // eslint-disable-next-line vue/return-in-computed-property
    cateId () {
      if (this.value.length === 3) {
        return this.value[this.value.length - 1]
      }
      return true
    },
    judgeData () {
      if (this.value.length === 3) {
        return false
      }
      return true
    }

  },
  mounted () {
    this.getCateList()
  }
}
</script>

<style scoped>
.input-new-tag{
  width: 100px;
}
.el-cascader{
  width: 300px;
  margin: 10px 0;
}
.el-tag{
  margin: 0 20px;
}
</style>
